<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('电表数据统计')" />
    <!-- 移除这里的ECharts引入 -->
</head>
<body class="gray-bg">
    <!-- 页面内容保持不变 -->
    
    <!-- 先引入基础JS库 -->
    <th:block th:include="include :: footer" />
    <!-- 再引入日期选择器 -->
    <th:block th:include="include :: datetimepicker" />
    <!-- 最后引入ECharts -->
    <th:block th:include="include :: echarts-js" />

    <script th:inline="javascript">
        var prefix = ctx + "system/meterdata";
        var statisticsChart = null; // 定义全局变量

        $(function() {
            // 初始化日期选择器
            $('#startTime').datetimepicker({
                format: 'YYYY-MM-DD',
                autoclose: true
            });
            $('#endTime').datetimepicker({
                format: 'YYYY-MM-DD',
                autoclose: true
            });

            // 默认查询日统计数据
            $('#statisticsType').val('day');
            var today = getNowFormatDate();
            $('#startTime').val(today);
            $('#endTime').val(today);

            // 确保ECharts已加载
            if (typeof echarts === 'undefined') {
                console.error("ECharts library not loaded.");
                $.modal.alertError("图表库加载失败，请刷新页面重试");
                return;
            }
            
            //initChart(); // 初始化图表
            //searchStatistics(); // 页面加载完成后立即执行一次查询
        });

        // 获取当前日期
        function getNowFormatDate() {
            var date = new Date();
            var seperator1 = "-";
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            var strDate = date.getDate();
            if (month >= 1 && month <= 9) {
                month = "0" + month;
            }
            if (strDate >= 0 && strDate <= 9) {
                strDate = "0" + strDate;
            }
            var currentdate = year + seperator1 + month + seperator1 + strDate;
            return currentdate;
        }

        // 初始化图表
        function initChart() {
            if (echarts) {
                statisticsChart = echarts.init(document.getElementById('statisticsChart'));
                var option = {
                    title: {
                        text: '统计数据'
                    },
                    tooltip: {},
                    legend: {
                        data:['数据']
                    },
                    xAxis: {
                        data: []
                    },
                    yAxis: {},
                    series: [{
                        name: '数据',
                        type: 'bar',
                        data: []
                    }]
                };
                statisticsChart.setOption(option);
            } else {
                console.error("ECharts library not loaded.");
            }
        }

        // 搜索统计数据
        // 搜索统计数据
        function searchStatistics() {
            var statisticsType = $('#statisticsType').val();
            var startTime = $('#startTime').val();
            var endTime = $('#endTime').val();
            var deviceId = "METER001"; // 默认设备ID，可以改为从表单获取
        
            // 根据统计类型选择不同的接口
            var url = "";
            var data = {};
            
            if (statisticsType === 'day') {
                url = prefix + "/statisticsByDay";
                data = {
                    deviceId: deviceId,
                    startDate: startTime,
                    endDate: endTime
                };
            } else if (statisticsType === 'week') {
                url = prefix + "/statisticsByWeek";
                data = {
                    deviceId: deviceId,
                    startDate: startTime,
                    endDate: endTime
                };
            } else if (statisticsType === 'month') {
                url = prefix + "/statisticsByMonth";
                data = {
                    deviceId: deviceId,
                    year: startTime.substring(0, 4) // 获取年份
                };
            } else if (statisticsType === 'year') {
                url = prefix + "/statisticsByYear";
                data = {
                    deviceId: deviceId,
                    startYear: startTime.substring(0, 4),
                    endYear: endTime.substring(0, 4)
                };
            }
        
            $.ajax({
                url: url,
                type: "POST", // 明确指定为POST请求
                data: data,
                dataType: "json", // 明确指定返回数据类型
                timeout: 60000, // 设置超时时间
                success: function(result) {
                    if (result.code == 0) {
                        updateChart(result.data, statisticsType);
                    } else {
                        $.modal.alertError(result.msg);
                    }
                },
                error: function(error) {
                    console.error("AJAX request failed: ", error);
                    $.modal.alertError("获取统计数据失败");
                    // 关闭加载层
                    $.modal.closeLoading();
                },
                complete: function() {
                    // 确保请求完成后关闭加载层
                    $.modal.closeLoading();
                }
            });
        }

        // 更新图表数据
        function updateChart(data, type) {
            if (!statisticsChart) {
                console.error("statisticsChart未初始化");
                return;
            }
        
            try {
                var xAxisData = [];
                var seriesData = [];
        
                if (data && data.length > 0) {
                    data.forEach(function(item) {
                        if (type === 'day') {
                            xAxisData.push(item.date); // 使用后端返回的字段名
                            seriesData.push(item.energy);
                        } else if (type === 'week') {
                            xAxisData.push(item.week + '周');
                            seriesData.push(item.energy);
                        } else if (type === 'month') {
                            xAxisData.push(item.month + '月');
                            seriesData.push(item.energy);
                        } else if (type === 'year') {
                            xAxisData.push(item.year + '年');
                            seriesData.push(item.energy);
                        }
                    });
                }
                
                var option = {
                    xAxis: {
                        data: xAxisData
                    },
                    series: [{
                        data: seriesData
                    }]
                };
                statisticsChart.setOption(option);
            } catch (e) {
                console.error("更新图表失败: ", e);
            }
        }
    </script>
</body>
</html>